﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Net;
using System.IO;
using System.Threading;
using System.Xml;

namespace UninstallHelper
{
    public partial class update : Form
    {
        public update()
        {
            InitializeComponent();
        }

        private void update_Load(object sender, EventArgs e)
        {
            Thread updaterThread = new Thread(new ThreadStart(Load_Updater));
            updaterThread.Start();
        }

        private void Load_Updater()
        {



            MethodInvoker LoadUpdater = delegate
            {
                //DEBUG
                string versionFile = "http://www.worxpace.de/uih/version.xml";
                IWebProxy proxy = WebRequest.GetSystemWebProxy();
                WebRequest requestVersionFile = WebRequest.Create(versionFile);
                requestVersionFile.Proxy = proxy;

                //updateDebugLbl1.Text = Convert.ToString(proxy);
                //updateDebugLbl2.Text = Convert.ToString(requestVersionFile.Proxy);

                if (CheckInternetConnect() == false)
                {
                    updaterLabel.Left = 158;
                    updaterLabel.Top = 127;
                    updaterLabel.Text = "Der Updateserver konnte nicht erreicht werden.";
                    updateBar.Value = 100;
                }
                else
                {
                    updaterLabel.Left = 200;
                    updaterLabel.Top = 127;
                    updaterLabel.Text = "Prüfe auf neue Version...";
                    updateBar.Value = 10;
                    if (CheckNewVersionAvailable() == true)
                    {
                        updaterLabel.Text = "Neue Version gefunden! Download?";
                        updateBar.Value = 100;
                        startUpdate.Visible = true;
                    }
                    else
                    {
                        updaterLabel.Text = "Keine neue Version gefunden!";
                        updateBar.Value = 100;
                        closeUpdate.Visible = true;
                    }
                }
            };
            Invoke(LoadUpdater);
        }

        public static bool CheckInternetConnect()
        {
            Ping ping = new Ping();
            try
            {
                PingReply reply = ping.Send("www.worxpace.de", 100);
                return reply.Status == IPStatus.Success;
            }
            catch
            {
                return false;
            }
        }
        public static bool CheckNewVersionAvailable()
        {
            string versionString = "0.5";
            bool newVersion = false;
            string versionFile = "http://www.worxpace.de/uih/version.xml";

            IWebProxy proxy = WebRequest.GetSystemWebProxy();
            WebRequest requestVersionFile = WebRequest.Create(versionFile);
            requestVersionFile.Proxy = proxy;

            WebResponse responseVersionFile = requestVersionFile.GetResponse();

            StreamReader xmlInputStream = new StreamReader(responseVersionFile.GetResponseStream());

            XmlTextReader xmlReader = new XmlTextReader(xmlInputStream);
            while (xmlReader.Read())
            {

                switch (xmlReader.Name)
                {
                    case "fileVersion":
                        Version actualVersion = new Version(versionString);
                        Version currentVersion = new Version(xmlReader.ReadString());
                        if (currentVersion <= actualVersion)
                        {
                            newVersion = false;

                        }
                        else
                        {
                            newVersion = true;

                        }
                        break;
                }
            }
            return newVersion;
        }

        private void closeUpdate_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void startUpdate_Click(object sender, EventArgs e)
        {
            startUpdate.Visible = false;
            Thread updateApp = new Thread(new ThreadStart(updateApplication));
            updateApp.Start();
        }
        private void updateApplication()
        {
            string fileName = "UninstallHelper.exe";
            string helperPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Worxpace");
            string updatePath = Path.Combine(helperPath, fileName);
            if (!Directory.Exists(helperPath))
            {
                Directory.CreateDirectory(helperPath);
            }
            MethodInvoker updateFileApplication = delegate
            {
                WebClient fileDownloader = new WebClient();
                fileDownloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                fileDownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                fileDownloader.DownloadFileAsync(new Uri("http://worxpace.de/uih/Uninstallhelper.exe"), updatePath);
            };
            Invoke(updateFileApplication);
        }
        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            updateBar.Value = e.ProgressPercentage;
        }
        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            updaterLabel.Text = "Update Erfolgreich";
            updateBar.Value = 100;
            closeUpdate.Visible = true;
        }
    }
}
